package net.siufung.market.base.user.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.siufung.core.result.Result;
import net.siufung.market.base.user.controller.model.dto.UserUpdatePasswdDto;
import net.siufung.market.base.user.controller.regulation.UserResetPasswdRegulation;
import net.siufung.market.base.user.controller.regulation.UserUpdatePasswdRegulation;
import net.siufung.market.base.user.mapper.IUserMapper;
import net.siufung.market.base.user.service.IUserService;
import net.siufung.security.api.service.passwd.ILoginPasswdService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户密码管理
 *
 * @author 陈建峰
 * @since 2022/6/29 5:46 下午
 */
@Api(tags = "用户密码管理")
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/sys/user/passwd")
public class UserPasswdController {

    private final IUserService userService;
    private final IUserMapper userMapper;
    private final ILoginPasswdService loginPasswdService;

    /**
     * 修改密码
     * @param userUpdatePasswdDto 密码修改属性
     * @return Result<Void>
     * */
    @ApiOperation(value = "修改密码")
    @PostMapping(value="/update")
    public Result<Boolean> update(
            @RequestBody UserUpdatePasswdDto userUpdatePasswdDto) {
        userUpdatePasswdDto.validated();
        UserUpdatePasswdRegulation userUpdatePasswdRegulation = new UserUpdatePasswdRegulation();
        userUpdatePasswdRegulation.isSatisfiedBy(userUpdatePasswdDto.getId());
        return Result.ok(userService.updatePasswd(
                userUpdatePasswdDto.getId(),
                loginPasswdService.encode(userUpdatePasswdDto.getNewPassword())));
    }

    /**
     * 重置密码
     * @param userId 用户ID
     * @return Result<Void>
     */
    @ApiOperation(value = "重置密码")
    @PostMapping(value = "/reset/{userId}")
    public Result<Boolean> resetPassword(@PathVariable("userId") Integer userId) {
        UserResetPasswdRegulation userResetPasswdRegulation = new UserResetPasswdRegulation(userMapper);
        userResetPasswdRegulation.isSatisfiedBy(userId);
        return Result.ok(userService.updatePasswd(
                userId,
                loginPasswdService.getInitPassword()));
    }
}
